﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Facebook;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Shell;
using System.Windows.Media.Imaging;
using System.IO;

namespace MolfMolfMolf
{
    public partial class FacebookAuth : PhoneApplicationPage
    {
        private FacebookClient client;
        private string accessToken;
        private string link;
        private Club currentClub;

        public FacebookAuth()
        {
            InitializeComponent();

            client = new FacebookClient();
            var parameters = new Dictionary<string, object>();
            parameters["client_id"] = IsolatedStorageSettings.ApplicationSettings["AppID"];
            parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
            parameters["response_type"] = "token";
            parameters["scope"] = "publish_stream";
            AuthBrowser.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(AuthBrowser_Navigated);
            AuthBrowser.Navigate(client.GetLoginUrl(parameters));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            link = null;
            currentClub = null;
            if (NavigationContext.QueryString.ContainsKey("link"))
            {
                link = NavigationContext.QueryString["link"];
            }
            else if (NavigationContext.QueryString.ContainsKey("clubid"))
            {
                currentClub = (Club)PhoneApplicationService.Current.State["club"];
            }
        }

        void AuthBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            FacebookOAuthResult result;
            if (!client.TryParseOAuthCallbackUrl(e.Uri, out result))
            {
                return;
            }

            if (result.IsSuccess)
            {
                accessToken = result.AccessToken;
                PhoneApplicationService.Current.State["accessToken"] = accessToken;
                if (link != null)
                {
                    postLink();
                }
                else if (currentClub != null)
                {
                    postClub();
                }
            }
            else
            {
                MessageBox.Show(result.ErrorDescription);
            }
        }

        private void postClub()
        {
            client = new FacebookClient(accessToken);

            client.PostCompleted += (o, e) =>
            {
                if (e.Error != null)
                {
                    Dispatcher.BeginInvoke(() => MessageBox.Show(e.Error.Message));
                    Dispatcher.BeginInvoke(() => NavigationService.GoBack());
                    return;
                }

                string result = e.GetResultData().ToString();
                Dispatcher.BeginInvoke(() => MessageBox.Show("Club Info Shared!"));
                Dispatcher.BeginInvoke(() => NavigationService.GoBack());
            };

            string message = String.Format("Club Name: {0}\nAddress: {1}, {2}\nHole Number: {3}\nHCP Required: {4}",
                currentClub.ClubName, currentClub.ClubAddress, currentClub.ClubCity, currentClub.ClubHoles, currentClub.ClubHCP);
            //var picture = new FacebookMediaObject
            //{
            //    ContentType = "image/jpeg",
            //    FileName = "Club Picture"
            //};
            //using (Stream stream = new MemoryStream())
            //{
            //    BitmapImage image = new BitmapImage() { CreateOptions = BitmapCreateOptions.None};
            //    image.UriSource = new Uri(String.Format("Images/{0}.png", currentClub.ClubId), UriKind.Relative);
            //    WriteableBitmap writableImage = new WriteableBitmap(image);
            //    Extensions.SaveJpeg(writableImage, stream, writableImage.PixelWidth, writableImage.PixelHeight, 0, 100);
            //    byte[] imageArray = new byte[stream.Length];
            //    stream.Position = 0;
            //    stream.Read(imageArray, 0, imageArray.Length);
            //    picture.SetValue(imageArray);
            //}
            client.PostAsync("me/feed", new { message = message, 
                /*place = new { id = "111984632161121", name = "Espoo, Finland", location = new { latitude = currentClub.ClubCoordinate.Latitude, longitude = currentClub.ClubCoordinate.Longitude } } */});
        }

        private void postLink()
        {
            client = new FacebookClient(accessToken);

            client.PostCompleted += (o, e) =>
            {
                if (e.Error != null)
                {
                    Dispatcher.BeginInvoke(() => MessageBox.Show(e.Error.Message));
                    return;
                }

            };

            client.PostAsync("me/links", new { link = link });
        }
    }
}